package com.example.teesystem.common.utils;


import lombok.experimental.UtilityClass;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

@UtilityClass
public class Url_ImageUtil {

    /**
     * 根据后缀判断是否为图片url
     */
    public boolean ValidImgType(String url) {
        if(!(url.endsWith("gif")||url.endsWith("jpg")||url.endsWith("jpeg")||url.endsWith("png")||url.endsWith("GIF")||url.endsWith("JPG")||url.endsWith("PNG"))){
            return false;
        }
        else{
            return true;
        }
    }

    /**
     * 判断文件为图片
     */
    public boolean IsImage(File file) throws IOException {
        BufferedImage bi = ImageIO.read(file);
        if(bi == null) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * 将MultipartFile转换为File
     * @param multiFile
     * @return
     */
    public static File MultipartFileToFile(MultipartFile multiFile) {
        // 获取文件名
        String fileName = multiFile.getOriginalFilename();
        // 获取文件后缀
        String prefix = fileName.substring(fileName.lastIndexOf("."));
        // 若须要防止生成的临时文件重复,能够在文件名后添加随机码

        try {
            File file = File.createTempFile(fileName, prefix);
            multiFile.transferTo(file);
            return file;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
